<template>
  <div class="article-container">
    <!-- 页面标题和操作区 -->
    <div class="page-header">
      <h1>文章管理</h1>
      <el-button type="primary" @click="showAddDialog">
        <el-icon><Plus /></el-icon>
        添加文章
      </el-button>
    </div>

    <!-- 筛选和搜索区域 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="分类">
          <el-select v-model="searchForm.categoryId" placeholder="请选择分类" clearable>
            <el-option v-for="category in categoryList" :key="category.id" :label="category.categoryName" :value="category.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.state" placeholder="请选择状态" clearable>
            <el-option label="草稿" value="草稿" />
            <el-option label="已发布" value="已发布" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getArticleList">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 文章列表表格 -->
    <el-card class="article-table-card">
      <div class="table-header">
        <el-button type="danger" @click="handleBatchDelete" :disabled="selectedArticleIds.length === 0">批量删除</el-button>
      </div>
      <el-table 
        v-loading="loading" 
        :data="articleList" 
        style="width: 100%" 
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" class-name="checkbox-column" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="categoryName" label="分类" width="120" />
        <el-table-column prop="state" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.state === '已发布' ? 'success' : 'info'">
              {{ row.state }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="coverImg" label="封面图" width="120">
          <template #default="{ row }">
            <el-image 
              v-if="row.coverImg" 
              :src="row.coverImg" 
              width="60" 
              height="60" 
              :preview-src-list="[row.coverImg]"
            />
            <span v-else class="no-image">无</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="showEditDialog(row.id)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑文章对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="800px"
      @close="resetForm"
    >
      <el-form ref="articleFormRef" :model="articleForm" :rules="formRules" label-width="100px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="articleForm.title" placeholder="请输入文章标题" />
        </el-form-item>
        <el-form-item label="所属分类" prop="categoryId">
          <el-select v-model="articleForm.categoryId" placeholder="请选择所属分类">
            <el-option v-for="category in categoryList" :key="category.id" :label="category.categoryName" :value="category.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="发布状态" prop="state">
          <el-select v-model="articleForm.state" placeholder="请选择发布状态">
            <el-option label="草稿" value="草稿" />
            <el-option label="已发布" value="已发布" />
          </el-select>
        </el-form-item>
        <el-form-item label="封面图片" prop="coverImg">
          <el-input v-model="articleForm.coverImg" placeholder="请输入封面图片URL" />
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <el-input 
            v-model="articleForm.content" 
            type="textarea" 
            placeholder="请输入文章内容" 
            rows="10"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, reactive, nextTick } from 'vue'
import { 
  ElButton, 
  ElTable, 
  ElTableColumn, 
  ElDialog, 
  ElForm, 
  ElFormItem, 
  ElInput, 
  ElMessageBox, 
  ElMessage, 
  ElIcon, 
  ElEmpty, 
  ElCard, 
  ElSelect, 
  ElOption, 
  ElPagination, 
  ElTag, 
  ElImage
} from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
// 导入配置好的axios实例
import request from '../utils/request'

// 移除mock数据导入，根据用户要求不使用本地模拟数据

// 导入模拟数据作为fallback，确保即使API不可用也能展示页面
const mockCategories = [
  { id: 16, categoryName: '旅游' },
  { id: 15, categoryName: '历史' },
  { id: 1, categoryName: '神话' }
]

export default {
  name: 'Article',
  components: {
    ElButton,
    ElTable,
    ElTableColumn,
    ElDialog,
    ElForm,
    ElFormItem,
    ElInput,
    ElEmpty,
    ElCard,
    ElIcon,
    ElSelect,
    ElOption,
    ElPagination,
    ElTag,
    ElImage,
    Plus
  },
  setup() {
    // 文章列表数据
    const articleList = ref([])
    // 分类列表数据
    const categoryList = ref(mockCategories)
    // 加载状态
    const loading = ref(false)
    // 对话框显示状态
    const dialogVisible = ref(false)
    // 对话框标题
    const dialogTitle = ref('')
    // 当前操作类型（add或edit）
    const operationType = ref('')
    // 当前编辑的文章ID
    const currentEditId = ref(null)
    // 选中的文章ID列表（用于批量删除）
    const selectedArticleIds = ref([])
    // 表单数据
    const articleForm = reactive({
      title: '',
      content: '',
      coverImg: '',
      state: '草稿',
      categoryId: ''
    })
    // 搜索表单数据
    const searchForm = reactive({
      categoryId: '',
      state: ''
    })
    // 分页数据
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    // 表单验证规则
    const formRules = reactive({
      title: [
        { required: true, message: '请输入文章标题', trigger: 'blur' },
        { min: 2, max: 50, message: '文章标题长度在 2 到 50 个字符', trigger: 'blur' }
      ],
      content: [
        { required: true, message: '请输入文章内容', trigger: 'blur' },
        { min: 10, message: '文章内容至少10个字符', trigger: 'blur' }
      ],
      categoryId: [
        { required: true, message: '请选择所属分类', trigger: 'change' }
      ],
      state: [
        { required: true, message: '请选择发布状态', trigger: 'change' }
      ],
      coverImg: [
        {
          pattern: /^$|^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/,
          message: '请输入合法的URL格式',
          trigger: 'blur'
        }
      ]
    })
    // 表单引用
    const articleFormRef = ref(null)

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    }

    // 处理表格选中项变化
    const handleSelectionChange = (selection) => {
      selectedArticleIds.value = selection.map(article => article.id)
    }

    // 处理分页大小变化
    const handleSizeChange = (size) => {
      pagination.pageSize = size
      getArticleList()
    }

    // 处理页码变化
    const handleCurrentChange = (current) => {
      pagination.currentPage = current
      getArticleList()
    }

    // 获取文章列表
    const getArticleList = async () => {
      loading.value = true
      try {
        const params = {
          pageNum: pagination.currentPage,
          pageSize: pagination.pageSize
        }
        
        // 添加可选参数
        if (searchForm.categoryId) {
          params.categoryId = searchForm.categoryId
        }
        if (searchForm.state) {
          params.state = searchForm.state
        }

        const res = await request.get('/article/list', { params })
        if (res.code === 0) {
          articleList.value = res.data.items || []
          pagination.total = res.data.total || 0
          // 为每个文章添加分类名称
          articleList.value.forEach(article => {
            const category = categoryList.value.find(cat => cat.id === article.categoryId)
            article.categoryName = category ? category.categoryName : ''
          })
        } else {
          ElMessage.error('获取文章列表失败：' + res.message)
          // 设置为空列表，不使用模拟数据
          articleList.value = []
          pagination.total = 0
        }
      } catch (error) {
        ElMessage.error('获取文章列表失败，请稍后再试')
        // 设置为空列表，不使用模拟数据
        articleList.value = []
        pagination.total = 0
      } finally {
        loading.value = false
      }
    }

    // 获取文章详情
    const getArticleDetail = async (id) => {
      try {
        const params = { id }
        const res = await request.get('/article/detail', { params })
        if (res.code === 0) {
          return res.data
        } else {
          // 从本地列表获取详情作为fallback
          const localArticle = articleList.value.find(article => article.id === id)
          if (!localArticle && res.message) {
            // 只有当本地没有数据且有具体错误信息时才显示提示
            ElMessage.error(res.message)
          }
          return localArticle ? localArticle : null
        }
      } catch (error) {
        // API请求失败时，尝试从本地获取数据
        const localArticle = articleList.value.find(article => article.id === id)
        return localArticle ? localArticle : null
      }
    }

    // 显示添加文章对话框
    const showAddDialog = () => {
      operationType.value = 'add'
      dialogTitle.value = '添加文章'
      resetForm()
      dialogVisible.value = true
    }

    // 显示编辑文章对话框
    const showEditDialog = async (id) => {
      try {
        operationType.value = 'edit'
        dialogTitle.value = '编辑文章'
        currentEditId.value = id
        
        const articleDetail = await getArticleDetail(id)
        if (articleDetail) {
          // 填充表单数据
          articleForm.title = articleDetail.title || ''
          articleForm.content = articleDetail.content || ''
          articleForm.coverImg = articleDetail.coverImg || ''
          articleForm.state = articleDetail.state || '草稿'
          articleForm.categoryId = articleDetail.categoryId || ''
          dialogVisible.value = true
        } else {
          ElMessage.error('无法获取文章详情')
        }
      } catch (error) {
        console.error('编辑文章失败:', error)
        ElMessage.error('打开编辑对话框失败')
      }
    }

    // 重置表单
    const resetForm = () => {
      if (articleFormRef.value) {
        articleFormRef.value.resetFields()
      }
      articleForm.title = ''
      articleForm.content = ''
      articleForm.coverImg = ''
      articleForm.state = '草稿'
      articleForm.categoryId = ''
      currentEditId.value = null
    }

    // 提交表单
    const handleSubmit = async () => {
      if (!articleFormRef.value) return
      try {
        await articleFormRef.value.validate()
        if (operationType.value === 'add') {
          await handleAdd()
        } else {
          await handleUpdate()
        }
      } catch (error) {
        return
      }
    }

    // 添加文章
    const handleAdd = async () => {
      try {
        const res = await request.post('/article/add', {
          title: articleForm.title,
          content: articleForm.content,
          coverImg: articleForm.coverImg,
          state: articleForm.state,
          categoryId: articleForm.categoryId
        })
        // 兼容code === 0和code === 1两种成功状态
        if (res.code === 0 || res.code === 1) {
          ElMessage.success('添加文章成功')
          dialogVisible.value = false
          getArticleList()
        } else {
          const errorMessage = res.message || '未知错误'
          ElMessage.error('添加文章失败：' + errorMessage)
        }
      } catch (error) {
        const errorMessage = error?.message || '网络错误'
        ElMessage.error('添加文章失败：' + errorMessage)
      }
    }

    // 更新文章
    const handleUpdate = async () => {
      try {
        const res = await request.put('/article/update', {
          id: currentEditId.value,
          title: articleForm.title,
          content: articleForm.content,
          coverImg: articleForm.coverImg,
          state: articleForm.state,
          categoryId: articleForm.categoryId
        })
        // 根据接口文档，成功的code应该是0
        if (res.code === 0) {
          ElMessage.success('更新文章成功')
          dialogVisible.value = false
          getArticleList()
        } else {
          const errorMessage = res.message || '未知错误'
          ElMessage.error('更新文章失败：' + errorMessage)
        }
      } catch (error) {
        ElMessage.error('更新文章失败：' + (error.message || '网络错误'))
      }
    }

    // 删除单篇文章
    const handleDelete = async (id) => {
      try {
        const confirmResult = await ElMessageBox.confirm(
          '确定要删除该文章吗？',
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        if (confirmResult === 'confirm') {
          await handleBatchDelete([id])
        }
      } catch (error) {
        if (error === 'cancel') return
        ElMessage.error('删除文章失败：' + error.message)
      }
    }

    // 批量删除文章
    const handleBatchDelete = async (ids = null) => {
      const deleteIds = ids || selectedArticleIds.value
      if (!deleteIds || deleteIds.length === 0) {
        ElMessage.warning('请选择要删除的文章')
        return
      }
      
      try {
        const res = await request.delete('/article/del', {
          data: deleteIds
        })
        if (res.code === 0) {
          ElMessage.success('删除文章成功')
          getArticleList()
          selectedArticleIds.value = []
        } else {
          ElMessage.error('删除文章失败：' + res.message)
        }
      } catch (error) {
        ElMessage.error('删除文章失败：' + error.message)
      }
    }

    // 页面加载时获取文章列表和分类列表
    onMounted(() => {
      getArticleList()
    })

    return {
      articleList,
      categoryList,
      loading,
      dialogVisible,
      dialogTitle,
      articleForm,
      searchForm,
      pagination,
      formRules,
      articleFormRef,
      selectedArticleIds,
      formatDate,
      showAddDialog,
      showEditDialog,
      resetForm,
      handleSubmit,
      handleDelete,
      handleBatchDelete,
      handleSizeChange,
      handleCurrentChange,
      handleSelectionChange
    }
  }
}
</script>

<style scoped>
.article-container {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
  background-color: #f5f7fa;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px 0;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.filter-card {
  background-color: #fff;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  padding: 15px 0;
}

.article-table-card {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-header {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 15px 0;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 20px;
  padding: 10px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.no-image {
  color: #909399;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 4px;
}

:deep(.el-table__header th) {
  background-color: #fafafa;
  font-weight: 600;
}

:deep(.el-table__body tr:hover > td) {
  background-color: #f5f7fa !important;
}

/* 按钮样式优化 */
:deep(.el-button) {
  border-radius: 4px;
}

:deep(.el-button--primary) {
  background-color: #409eff;
  border-color: #409eff;
}

:deep(.el-button--primary:hover) {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

:deep(.el-button--danger) {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

:deep(.el-button--danger:hover) {
  background-color: #f78989;
  border-color: #f78989;
}

/* 复选框样式优化 - 添加黑点显示 */
:deep(.el-table .checkbox-column .el-checkbox__inner) {
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.2) !important;
  border-color: #dcdfe6;
}

/* 复选框选中时显示黑点 */
:deep(.el-checkbox__input.is-checked .el-checkbox__inner::after) {
  content: '';
  display: block;
  position: absolute;
  top: 50%;
  left: 50%;
  width: 8px;
  height: 8px;
  background-color: #fff;
  border-radius: 50%;
  transform: translate(-50%, -50%);
}

:deep(.el-checkbox__inner:hover) {
  border-color: #409eff;
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #409eff;
  border-color: #409eff;
}
</style>